import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import relativeTime from 'dayjs/plugin/relativeTime'
dayjs.extend(relativeTime) // 相对时间
dayjs.locale('zh-cn') // 使用本地化语言
/**
 * 格式化数字
 * @param {number} number 数字
 * @returns
 */
export const formatNumber = (number: number) => {
  const str = number.toString()
  const ind = str.length % 3
  const strFront = str.slice(0, ind)
  const strBehind = str.slice(ind)
  const arr = []
  for (let i = 0; i < strBehind.length; i += 3) {
    arr.push(strBehind.slice(i, i + 3))
  }
  if (ind) {
    arr.unshift(strFront)
  }
  return arr.join()
}

const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm:ss'
const DATE_FORMAT = 'YYYY-MM-DD'
const TIME_FORMAT = 'HH:mm:ss'
//时间转日期
export const formatToDateTime = (date: number, format = DATE_TIME_FORMAT): string => {
  return dayjs(date).format(format)
}

export const formatToDate = (date: number, format = DATE_FORMAT): string => {
  return dayjs(date).format(format)
}
export const formatToTime = (date: number, format = TIME_FORMAT): string => {
  return dayjs(date).format(format)
}
//日期转时间
export const formatToUnix = (date: string): number => {
  return dayjs(date).unix()
}
export const dateUtil = dayjs
/*
 * @param time 时间字符串
 * @param friendly 显示xxx时间前 (显示为几分钟前 几小时前 几天前 几个月前 )
 */
export function getLastTimeStr(time: string, friendly: boolean) {
  if (friendly) {
    return dayjs(time).fromNow().replace(' ', '')
  }
  return dayjs(new Date(time)).format('YYYY-MM-DD HH:mm')
}
const WEEK_LIST: Record<string, any> = {
  '1': '一',
  '2': '二',
  '3': '三',
  '4': '四',
  '5': '五',
  '6': '六',
  '7': '日'
}
//由星期的数字转换为星期的名称,date格式：2016-01-07，用"-"分割
export const weekDay = function (time: string) {
  const timeArr = time.split(',')
  let str = ''
  timeArr.forEach((item: string, index: number) => {
    if (timeArr.length - 1 == index) {
      str += WEEK_LIST[item]
    } else {
      str += WEEK_LIST[item] + '/'
    }
  })
  return str
}
